﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Web.Http;
using hlib.IO;
using SalesSys.BLL;
using SalesSys.Comm.BLL;
using SalesSys.DAL.Models;
using SalesSys.WebCore;
using SalesSys.WebCore.Authorize;
using SalesSys.BLL.Sales;
using SalesSys.Service.Purchasing;
using System.Linq;
using SalesSys.Comm.DAL;
using SalesSys.DAL;
using System.Data.Entity;
using System.Runtime.Serialization;
using System.Web;
using System.Data;

namespace SalesSys.Site.Controllers.Api
{
    /// <summary>
    /// 报表
    /// </summary>
    [RoutePrefix("api/Report")]
    public class ReportController : BaseApiController
    {
        private OrderBLL orderBll = BllFactory.GetBll<OrderBLL>();
        private LockOrderBLL lockOrderBll = BllFactory.GetBll<LockOrderBLL>();
        private ProviderBLL providerBLL = BllFactory.GetBll<ProviderBLL>();
        InfoCollectionBLL infoBLL = BllFactory.GetBll<InfoCollectionBLL>();
        private NowDepotProfitReportBLL nowDepotProfitReportBLL = new NowDepotProfitReportBLL();
        private CommodityInfoBLL commodityInfoBll = BllFactory.GetBll<CommodityInfoBLL>();
        /// <summary>
        /// 计划单列表
        /// </summary>
        /// <param name="page">分页</param>
        /// <param name="rows">每页条数</param>
        /// <param name="state">计划单状态</param>
        /// <param name="keyword">供应商\客户全称\客户简称，模糊查询</param>
        [Route("DailySales")]
        public ViewDto<IEnumerable<Order>> DailySales(int page, int rows, OrderState? state = null, string keyword = null)
        {
            try
            {
                var empId = ClientHelper.ClientInfo.Id;
                var re = orderBll.Select(keyword, state, new QueryInfo { Page = page, Rows = rows });
                var dto = new ViewDto<IEnumerable<Order>>();
                dto.Data = re.Value;

                dto.Total = re.Key;
                dto.Page = page;
                dto.Rows = rows;
                return dto;
            }
            catch (Exception)
            {

                throw;
            }

        }

        /// <summary>
        /// 应收账款报表
        /// </summary>
        /// <returns></returns>
        [Route("Receivable")]
        public object[][] Receivable()
        {
            return orderBll.Receivable();
        }

        /// <summary>
        /// 销售日报表
        /// </summary>
        /// <param name="createTime">查询日期</param>
        /// <param name="dept">部门编号</param>
        [Route("DayOrder")]
        [HttpGet]
        public ViewDto<IEnumerable<Order>> DayOrder(DateTime? createTime = null, Guid? dept = null)
        {
            try
            {
                var empId = ClientHelper.ClientInfo.Id;

                var day = DateTime.Now;
                if (createTime != null)
                    day = Convert.ToDateTime(createTime);
                //查询所有已结算
                var total = 0;
                var dto = new ViewDto<IEnumerable<Order>>();
                List<Order> orderList = new List<Order>();

                if (dept != null)
                {
                    orderList =
                      orderBll.GetList(
                          p => p.Creater.Department.Id == dept.Value &&
                              p.IsSettlement &&
                              DbFunctions.TruncateTime(p.SettlementTime) == DbFunctions.TruncateTime(day)).ToList();
                    GetAllDeptUser(dept.Value, day, ref orderList);

                }
                else
                {
                    orderList =
                        orderBll.GetList(
                            p =>
                                p.IsSettlement &&
                                DbFunctions.TruncateTime(p.SettlementTime) == DbFunctions.TruncateTime(day)).ToList();
                }

                dto.Data = orderList;
                return dto;
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 根据部门编号查询部门所有人员，递归
        /// </summary>
        /// <param name="parentGuid">部门编号</param>
        /// <param name="day">查询日期</param>
        /// <param name="result">返回结果</param>
        private void GetAllDeptUser(Guid parentGuid, DateTime? day, ref List<Order> result)
        {
            var bll = BllFactory.GetBll<EmployeeBLL>();
            var total = 0;
            var currentDeptList = bll.GetDepartmentListByParentGuid(parentGuid);
            if (currentDeptList != null && currentDeptList.Length > 0)
            {
                foreach (var dept in currentDeptList)
                {
                    var orderList = orderBll.GetList(p => p.Creater.Department.Id == dept.Id && p.IsSettlement && DbFunctions.TruncateTime(p.SettlementTime) == DbFunctions.TruncateTime(day), out total, "CreateTime", false, 1, 999999999).ToList();
                    if (orderList.Count > 0)
                    {
                        result.AddRange(orderList);
                    }
                    GetAllDeptUser(dept.Id, day, ref result);
                }
            }
        }

        #region 导出报表
        /// <summary>
        /// 销售日报表
        /// </summary>
        /// <param name="createTime">查询日期</param>
        /// <param name="dept">部门编号</param>
        /// <returns></returns>
        [Route("ExpDayOrder")]
        [HttpGet]
        public HttpResponseMessage ExpDayOrder(string createTime, Guid? dept)
        {
            var day = DateTime.Now;
            if (createTime != null)
                day = Convert.ToDateTime(createTime);
            //查询所有已结算
            List<Order> orderList = new List<Order>();

            if (dept != null)
            {
                orderList =
                  orderBll.GetList(
                      p => p.Creater.Department.Id == dept.Value &&
                          p.IsSettlement &&
                          DbFunctions.TruncateTime(p.SettlementTime) == DbFunctions.TruncateTime(day)).ToList();
                GetAllDeptUser(dept.Value, day, ref orderList);
            }
            else
            {
                orderList =
                    orderBll.GetList(
                        p =>
                            p.IsSettlement &&
                            DbFunctions.TruncateTime(p.SettlementTime) == DbFunctions.TruncateTime(day)).ToList();
            }

            HttpResponseMessage msg = null;
            var expData = new List<List<string>>();
            foreach (var ord in orderList)
            {
                foreach (var commodity in ord.CommodityInfos)
                {
                    var data = new List<String>();
                    var price = commodity.Price - ord.UnitTotal - ord.ApplyDiscount;
                    data.Add(ord.Id.ToString());
                    data.Add(ord.CreateTime.ToShortDateString());
                    data.Add(ord.Customer.ShortName);
                    data.Add(ord.Account.Name);
                    data.Add(commodity.Commodity.FillName());
                    data.Add("");
                    data.Add(commodity.Count.ToString());
                    data.Add(price.ToString());
                    data.Add((price * commodity.Count).ToString());
                    data.Add(ord.VehicleInfos);
                    data.Add(ord.District.FillName);
                    data.Add(ord.IsPublicDelivery ? "0" : (ord.DeliveryPrice * commodity.Count).ToString());
                    data.Add(ord.IsPublicDelivery ? (ord.DeliveryPrice * commodity.Count).ToString() : "0");
                    data.Add(ord.Provider.Supplier == null ? "" : ord.Provider.Supplier.Brand);
                    data.Add(ord.Provider.Name);
                    data.Add(ord.Remarks);
                    data.Add("");
                    data.Add(ord.CreateTime.ToShortDateString());
                    data.Add(ord.Creater.Department.Name);
                    data.Add("");
                    expData.Add(data);
                }
            }

            var nameArray = new string[] { "id", "日期", "客户名称", "户头", "品种/规格", "税", "销售数量", "销售价格", 
                "销售金额", "车号", "目的地", "不冲账运费", "冲账运费", "供货厂家", "库房", "备注", "户头", "日期", "事业部","户头" };

            msg = CsvExp("销售日报表.csv", expData, nameArray);
            return msg;
        }
        #endregion

        private IPurchasingSvc purchasingSvc = new PurchasingSvc();

        /// <summary>
        /// 采购明细报表
        /// </summary>
        /// <param name="page">分页</param>
        /// <param name="rows">每页条数</param>
        /// <param name="createTime">创建时间</param>
        /// <param name="name">厂家名称</param>
        [Route("PurchaseReport")]
        public ViewDto<IEnumerable<string[]>> GetPurchaseReport(DateTime? createTime = null, string name = null, int page = 1, int rows = 10)
        {
            try
            {
                int total = 0;
                var data = purchasingSvc.GetPurchaseReportArray(name, createTime, null, page, rows, out total);
                string[][] result = new string[data.Count() + 1][];
                result[0] = new string[] { "日期", "厂家", "品种", "是否标件", "规格", "数量", "单价", "金额", "库房", "户头", "公司", "备注" };
                data.CopyTo(result, 1);
                var dto = ViewDto.CreateList(result);
                dto.Page = page;
                dto.Rows = rows;
                dto.Total = total;

                return dto;
            }
            catch (Exception e)
            {

                throw;
            }

        }

        /// <summary>
        /// 采购明细报表导出
        /// </summary>
        /// <param name="createTime">查询日期</param>
        /// <param name="name">名称</param>
        /// <returns></returns>
        [Route("ExpPurchaseReport")]
        [HttpGet]
        public HttpResponseMessage ExpPurchaseReport(string createTime = null, string name = null)
        {
            int total = 0;
            DateTime? query_time = null;
            if (!string.IsNullOrEmpty(createTime))
            {
                query_time = Convert.ToDateTime(createTime);
            }
            var data = purchasingSvc.GetPurchaseReportArray(name, query_time, null, 1, 19999, out total);

            HttpResponseMessage msg = null;
            var nameArray = new string[] { "日期", "厂家", "品种", "是否标件", "规格", "数量", "单价", "金额", "库房", "户头", "公司", "备注" };

            msg = CsvExp("采购明细报表.csv", data, nameArray);
            return msg;
        }

        /// <summary>
        /// 应收账款报表查询
        /// </summary>
        /// <param name="settlementTime"></param>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <returns></returns>
        [Route("DebtReport")]
        [HttpGet]
        public ViewDto<IEnumerable<string[]>> DebtReport(DateTime? settlementTime = null, bool isHand = true, int page = 1, int rows = 10)
        {
            try
            {
                int total = 0;
                var data = orderBll.GetDebtReportArray(settlementTime, page, rows, out total);
                if (isHand)
                {
                    var nameArray = new string[] { "序号", "事业部", "客户专员", "客户", "欠款金额", "账期" };
                    var list = new List<string[]>();
                    list.Add(nameArray);
                    list.AddRange(data);
                    data = list.ToArray();
                }
                //string[][] result = new string[data.Count() + 1][];
                //result[0] = new string[] { "序号", "事业部", "客户专员", "客户", "欠款金额", "账期", "滞纳金（元）" };
                //data.CopyTo(result, 1);
                var dto = ViewDto.CreateList(data);
                dto.Page = page;
                dto.Rows = rows;
                dto.Total = total;

                return dto;
            }
            catch (Exception e)
            {
                throw;
            }
        }

        /// <summary>
        /// 应收账款报表导出
        /// </summary>
        /// <returns></returns>
        [Route("ExpDebtReport")]
        [HttpGet]
        public HttpResponseMessage ExpDebtReport(DateTime? settlementTime = null)
        {
            int total = 0;
            var data = orderBll.GetDebtReportArray(settlementTime, 1, 19999, out total);

            HttpResponseMessage msg = null;
            var nameArray = new string[] { "序号", "事业部", "客户专员", "客户", "欠款金额", "账期" };//, "滞纳金（元）"

            msg = CsvExp("应收账款滞纳金考核明细表.csv", data, nameArray);

            return msg;
        }

        /// <summary>
        /// 采购销售情况报表
        /// </summary>
        /// <param name="createTime"></param>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        [Route("PurchaseReport")]
        public void PurchaseReport(int page, int rows, DateTime? createTime = null)
        {
            var orderList = orderBll.GetList(p => p.IsSettlement).OrderBy(p => p.Provider.Name);

            DateTime monthDate = DateTime.Now.AddDays(-Convert.ToInt32(DateTime.Now.Date.Day) + 1).Date;
            DateTime dayDate = DateTime.Now.Date;
            if (createTime != null)
            {
                dayDate = createTime.Value.Date;
            }
            DateTime addDate = dayDate.AddDays(1);

            // 按照厂家分组计算日销量
            var dayWeight = orderList.Where(p => p.CreateTime >= dayDate && p.CreateTime < addDate).GroupBy(p => p.Provider)
                .Select(g => new
                {
                    ProviderId = g.Key.Id,
                    ProviderName = g.Key.Name,
                    DayWeight = g.Sum(x => x.Weight)
                }).ToArray();

            // 按照厂家分组计算当月累计销量
            var sumWeight = orderList.Where(p => p.CreateTime > monthDate)
                .GroupBy(p => p.Provider)
                .Select(g => new
                {
                    ProviderId = g.Key.Id,
                    ProviderName = g.Key.Name,
                    SumWeight = g.Sum(x => x.Weight)
                }).ToArray();

            var result = from a in dayWeight
                         join b in sumWeight on a.ProviderId equals b.ProviderId
                         select new
                         {
                             ProviderId = a.ProviderId,
                             ProviderName = a.ProviderName,
                             DayWeight = a.DayWeight,
                             SumWeight = b.SumWeight
                         };

            // 计算厂家当月总计锁价金额
            var SumToal = lockOrderBll.GetList(p => p.CreateTime > monthDate && p.IsGoodsLock)
                .GroupBy(p => p.Provider.Id)
                .Select(g => new
                {
                    ProviderId = g.Key,
                    SumToal = g.Sum(p => p.Total)
                }).ToArray();
        }

        /// <summary>
        /// 指定日期的库存进销差
        /// </summary>
        /// <param name="dt"></param>
        [HttpGet]
        [Route("NowDepotProfit")]
        public object[][] NowDepotProfit(DateTime? dt = null)
        {
            var sysBll = new SysConfigBLL();
            var list = sysBll.GetTableView("NowDepotProfit");
            var sumData = new object[8];
            sumData[0] = " -- ";
            sumData[1] = "总计";
            for (int i = 2; i < 8; i++)
            {
                sumData[i] = list.Skip(1).Sum(p => Todecimal(p[i], 0));
            }
            var data = new List<object[]>(list);
            data.Add(sumData);
            for (int i = 1; i < data.Count; i++)
            {
                for (int j = 2; j < data[i].Length; j++)
                {
                    data[i][j] = (Todecimal(data[i][j], 0)).ToString("####");
                }
            }
            return data.ToArray();
        }

        public decimal Todecimal(object obj, decimal def = 0)
        {
            if (obj is decimal)
            {
                return (decimal)obj;
            }
            decimal.TryParse(obj + "", out def);
            return def;
        }

        /// <summary>
        /// 查询每日成交总量
        /// </summary>
        /// <param name="begin"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        [Route("SelectVolumeTotal")]
        [HttpGet]
        public string[][] SelectVolumeTotal(DateTime begin, DateTime end)
        {
            var data = orderBll.SelectVolumeTotal(begin, end);
            var list = new List<string[]>();
            list.Add(new[] { "日期", "成交量" });
            list.AddRange(data);
            return list.ToArray();
        }
        /// <summary>
        /// 获取当前仓库成本信息
        /// </summary>
        /// <param name="isHander"></param>
        /// <returns></returns>
        [Route("GetDepotInfo")]
        [HttpGet]
        public object[][] GetDepotInfo(bool isHander = true)
        {
            var bll = new ReportBLL();
            return bll.GetDepotInfo(isHander);
        }

        [Route("GetDayOrderList")]
        [HttpGet]
        public object[][] GetDayOrderList(bool isHander = true, Guid? deptId = null, DateTime? settlementTime = null)
        {
            var bll = new ReportBLL();
            string deptNames = "";
            //获取所有子部门名称
            if (deptId.HasValue)
            {
                GetChildrenDept(deptId.Value, ref  deptNames);
            }
            return bll.GetDayOrderList(isHander, deptNames, settlementTime);
        }

        private void GetChildrenDept(Guid deptId, ref string deptNames)
        {
            var bll = BllFactory.GetBll<EmployeeBLL>();
            //获取当前部门
            var department = bll.GetDepartment(deptId);
            deptNames += "'" + department.Name + "',";
            var currentDeptList = bll.GetDepartmentListByParentGuid(deptId);
            if (currentDeptList != null && currentDeptList.Length > 0)
            {
                foreach (var dept in currentDeptList)
                {
                    deptNames += "'" + dept.Name + "',";
                    GetChildrenDept(dept.Id, ref deptNames);
                }
            }
            deptNames = deptNames.TrimEnd(',');
        }
        /// <summary>
        /// 日销售底表
        /// </summary>
        /// <param name="page">分页</param>
        /// <param name="rows">每页条数</param>
        [Route("ManagementDay")]
        [HttpGet]
        public ViewDto<IEnumerable<Order>> ManagementDay(int page, int rows, DateTime? createTime = null, Guid? dept = null)
        {
            try
            {
                var empId = ClientHelper.ClientInfo.Id;

                var day = DateTime.Now;
                if (createTime != null)
                    day = Convert.ToDateTime(createTime);
                //查询所有当天经营日报
                var total = 0;
                var dto = new ViewDto<IEnumerable<Order>>();
                List<Order> orderList = new List<Order>();

                if (dept != null)
                {
                    orderList =
                      orderBll.GetList(
                          p => p.Creater.Department.Id == dept.Value &&
                              DbFunctions.TruncateTime(p.CreateTime) == DbFunctions.TruncateTime(day), out total,
                          "CreateTime", false, page, rows).ToList();
                    GetAllDeptUserManagementDay(dept.Value, day, ref orderList);
                    total = orderList.Count;
                }
                else
                {
                    orderList =
                        orderBll.GetList(
                            p => DbFunctions.TruncateTime(p.CreateTime) == DbFunctions.TruncateTime(day), out total,
                            "CreateTime", false, page, rows).ToList();
                }
                dto.Data = orderList;
                dto.Total = total;
                dto.Page = page;
                dto.Rows = rows;
                return dto;
            }
            catch (Exception)
            {

                throw;
            }
        }
        private void GetAllDeptUserManagementDay(Guid parentGuid, DateTime? day, ref List<Order> result)
        {
            var bll = BllFactory.GetBll<EmployeeBLL>();
            var total = 0;
            var currentDeptList = bll.GetDepartmentListByParentGuid(parentGuid);
            if (currentDeptList != null && currentDeptList.Length > 0)
            {
                foreach (var dept in currentDeptList)
                {
                    var orderList = orderBll.GetList(p => p.Creater.Department.Id == dept.Id && DbFunctions.TruncateTime(p.CreateTime) == DbFunctions.TruncateTime(day), out total, "CreateTime", false, 1, 999999999).ToList();
                    if (orderList.Count > 0)
                    {
                        result.AddRange(orderList);
                    }
                    GetAllDeptUserManagementDay(dept.Id, day, ref result);
                }
            }
        }
        #region 导出日销售底表
        /// <summary>
        /// 日销售底表
        /// </summary>
        /// <returns></returns>
        [Route("ExpManagementDay")]
        [HttpGet]
        public HttpResponseMessage ExpManagementDay(DateTime? createTime = null, Guid? dept = null)
        {
            var day = DateTime.Now;
            if (createTime != null)
                day = Convert.ToDateTime(createTime);
            //查询所有当天经营日报
            List<Order> orderList = new List<Order>();
            if (dept != null)
            {
                orderList =
                  orderBll.GetList(
                      p => p.Creater.Department.Id == dept.Value &&
                          DbFunctions.TruncateTime(p.CreateTime) == DbFunctions.TruncateTime(day)).ToList();
                GetAllDeptUserManagementDay(dept.Value, day, ref orderList);
            }
            else
            {
                orderList =
                    orderBll.GetList(
                        p => DbFunctions.TruncateTime(p.CreateTime) == DbFunctions.TruncateTime(day)).ToList();
            }
            HttpResponseMessage msg = null;
            var expData = new List<List<string>>();
            foreach (var ord in orderList)
            {
                foreach (var commodity in ord.CommodityInfos)
                {
                    var data = new List<String>();
                    var price = commodity.Price - ord.UnitDiscount - ord.ApplyDiscount;
                    data.Add(ord.Id.ToString());
                    data.Add(ord.CreateTime.ToShortDateString());
                    data.Add(ord.Customer.ShortName);
                    data.Add(ord.Account.Name);
                    data.Add(commodity.Commodity.FillName());
                    data.Add("");
                    data.Add(commodity.Weight.ToString());
                    data.Add(price.ToString());
                    data.Add((price * commodity.Weight).ToString("f2"));
                    data.Add(ord.VehicleInfos);
                    data.Add(ord.District.FillName);
                    data.Add(ord.IsPublicDelivery ? "0" : (ord.DeliveryPrice * commodity.Weight).ToString("f2"));
                    data.Add(ord.IsPublicDelivery ? (ord.DeliveryPrice * commodity.Weight).ToString("f2") : "0");
                    data.Add(commodity.Commodity.Brand);
                    data.Add(ord.Provider.Name);
                    data.Add(ord.Remarks);
                    data.Add("");
                    data.Add(ord.CreateTime.ToShortDateString());
                    data.Add(ord.Creater.Department.Name);
                    data.Add(ord.State.GetDescription());
                    expData.Add(data);
                }
            }

            var nameArray = new string[] { "id", "日期", "客户名称", "户头", "品种/规格", "税", "销售重量", "销售价格", 
                "销售金额", "车号", "目的地", "不冲账运费", "冲账运费", "供货厂家", "库房", "备注", "户头", "日期", "事业部","状态" };

            msg = CsvExp(day.ToShortDateString() + "日销售底表.csv", expData, nameArray);
            return msg;
        }
        #endregion


        /// <summary>
        /// 日使用情况报表查询
        /// </summary>
        /// <param name="settlementTime"></param>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <returns></returns>
        [Route("DailyUsage")]
        [HttpGet]
        public string[][] DailyUsage(DateTime? createTime = null, Guid? deptId = null, bool isHand = true)
        {
            try
            {
                var bll = new ReportBLL();
                string deptNames = "";
                //获取所有子部门名称
                if (deptId.HasValue)
                {
                    GetChildrenDept(deptId.Value, ref  deptNames);
                }
                var data = orderBll.GetDailyUsage(createTime, deptNames);
                var list = new List<string[]>();
                list.Add(new[] { "事业部", "客户专员", "待确认", "审核通过", "驻厂确认", "已发货", "已收货", "已结算", "完结", "取消", "已退货", "已退款" });
                list.AddRange(data);
                return list.ToArray();
            }
            catch (Exception e)
            {
                throw;
            }
        }

        /// <summary>
        /// 日使用情况报表导出
        /// </summary>
        /// <returns></returns>
        [Route("ExpDailyUsage")]
        [HttpGet]
        public HttpResponseMessage ExpDailyUsage(DateTime? createTime = null, Guid? deptId = null, bool isHand = true)
        {
            var bll = new ReportBLL();
            string deptNames = "";
            //获取所有子部门名称
            if (deptId.HasValue)
            {
                GetChildrenDept(deptId.Value, ref  deptNames);
            }
            var data = orderBll.GetDailyUsage(createTime, deptNames);

            HttpResponseMessage msg = null;
            var list = new List<string[]>();
            list.Add(new[] { "事业部", "客户专员", "待确认", "审核通过", "驻厂确认", "已发货", "已收货", "已结算", "完结", "取消", "已退货", "已退款" });
            list.AddRange(data);

            msg = CsvExp("日使用情况.csv", list.ToArray());
            return msg;
        }

        //----------------------------------------------日经营分析报告 Start-----------------------------------------------------------
        /// <summary>
        /// 采销情况
        /// </summary>
        /// <param name="isHander"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="providerType"></param>
        /// <returns></returns>
        [Route("GetSalesReport")]
        [HttpGet]
        public SalesReport[] GetSalesReport(bool isHander = true, DateTime? startTime = null, DateTime? endTime = null, int? providerType = null)
        {
            var bll = new SalesReportBLL();
            return bll.GetSalesReportList(isHander, startTime, endTime, providerType).ToArray();
        }

        /// <summary>
        /// 采销情况-导出
        /// </summary>
        /// <param name="isHander"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="providerType"></param>
        /// <returns></returns>
        [Route("ExpSalesReport")]
        [HttpGet]
        public HttpResponseMessage ExpSalesReport(bool isHander = true, DateTime? startTime = null, DateTime? endTime = null, int? providerType = null)
        {
            var bll = new SalesReportBLL();
            var result = bll.GetSalesReportList(isHander, startTime, endTime, providerType);

            var expData = new List<List<string>>();
            HttpResponseMessage msg = null;
            var nameArray = new string[] { "供应商类型", "供应商单位名称", "今日销售数量", "累计销售数量", "累计预销售数量", "当日毛利额", "累计毛利额", "返利金额", "累计采购量", "合计锁货数量", "厂家余款" };

            foreach (var item in result)
            {
                var data = new List<String>();
                data.Add(item.ProviderType.ToString());
                data.Add(item.Name);
                data.Add(item.DayCount.ToString());
                data.Add(item.TotalCount.ToString());
                data.Add(item.OldTotalCount.ToString());
                data.Add(item.DayProfit.ToString());
                data.Add(item.TotalProfit.ToString());
                data.Add(item.RebateMoney.ToString());
                data.Add(item.TotalPurchase.ToString());
                data.Add(item.LockGoodsCount.ToString());
                data.Add(item.BalanceMoney.ToString());
                expData.Add(data);
            }


            msg = CsvExp("日经营分析报告-采销情况.csv", expData.ToArray(), nameArray);
            return msg;
        }

        /// <summary>
        /// 应收账务
        /// </summary>
        /// <param name="isHander"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="deptId"></param>
        /// <returns></returns>
        [Route("GetAccountsReportList")]
        [HttpGet]
        public AccountsReport[] GetAccountsReportList(bool isHander = true, DateTime? startTime = null, DateTime? endTime = null, Guid? deptId = null)
        {
            var bll = new AccountsReportBLL();
            List<AccountsReport> accountsList = new List<AccountsReport>();
            accountsList = bll.GetAccountsReportList(isHander, startTime, endTime, deptId).ToList();
            GetAllDeptAccountsReport(isHander, deptId.Value, startTime, endTime, ref accountsList);
            return accountsList.ToArray();
        }



        private void GetAllDeptAccountsReport(bool isHander, Guid parentGuid, DateTime? startTime, DateTime? endTime, ref List<AccountsReport> result)
        {
            var bll = new EmployeeBLL();
            var bllAccount = new AccountsReportBLL();
            var total = 0;
            var currentDeptList = bll.GetDepartmentListByParentGuid(parentGuid);
            if (currentDeptList != null && currentDeptList.Length > 0)
            {
                foreach (var dept in currentDeptList)
                {
                    List<AccountsReport> accountsList = bllAccount.GetAccountsReportList(isHander, startTime, endTime, dept.Id).ToList();
                    if (accountsList.Count > 0)
                    {
                        result.AddRange(accountsList);
                    }
                    GetAllDeptAccountsReport(isHander, dept.Id, startTime, endTime, ref accountsList);
                }
            }
        }




        /// <summary>
        /// 应收账务-导出
        /// </summary>
        /// <param name="isHander"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="deptId"></param>
        /// <returns></returns>
        [Route("ExpAccountsReport")]
        [HttpGet]
        public HttpResponseMessage ExpAccountsReport(bool isHander = true, DateTime? startTime = null, DateTime? endTime = null, Guid? deptId = null)
        {
            var bll = new AccountsReportBLL();
            var result = bll.GetAccountsReportList(isHander, startTime, endTime, deptId);

            var expData = new List<List<string>>();
            HttpResponseMessage msg = null;
            var nameArray = new string[] { "分公司名称", "客户经理", "客户名称", "应收金额", "2日以上应收金额", "账龄" };

            foreach (var item in result)
            {
                var data = new List<String>();
                data.Add(item.DepartName);
                data.Add(item.CreateName);
                data.Add(item.CustomName);
                data.Add(item.RealPrice.ToString());
                data.Add(item.TwodaysRealPrice.ToString());
                data.Add(item.AgingDay.ToString());
                expData.Add(data);
            }
            msg = CsvExp("日经营分析报告-应收账务.csv", expData.ToArray(), nameArray);
            return msg;
        }

        /// <summary>
        /// 应收账务-公户私户统计
        /// </summary>
        /// <param name="isHander"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="deptId"></param>
        /// <returns></returns>
        [Route("GetAccountsTypeReportList")]
        [HttpGet]
        public AccountsTypeReport[] GetAccountsTypeReportList(bool isHander = true, DateTime? startTime = null, DateTime? endTime = null, Guid? deptId = null)
        {
            var bll = new AccountsTypeReportBLL();
            return bll.GetAccountsTypeReportList(isHander, startTime, endTime, deptId).ToArray();
        }
        /// <summary>
        /// 日经营分析报表-库存权益-获取品牌统计
        /// </summary>
        /// <returns></returns>
        [Route("GetSupplierReportList")]
        [HttpGet]
        public NowDepotProfitReportShow[] GetSupplierReportList()
        {
            var bll = new NowDepotProfitReportBLL();
            List<NowDepotProfitReport> result = nowDepotProfitReportBLL.GetSupplierReportList().ToList();

            List<NowDepotProfitReportShow> resultShow = new List<NowDepotProfitReportShow>();
            if (result != null && result.Count > 0)
            {
                foreach (var item in result)
                {
                    NowDepotProfitReportShow result_show = new NowDepotProfitReportShow();
                    result_show.cangku = item.仓库;
                    result_show.cangkuId = item.仓库ID;
                    result_show.changjia = item.厂家;
                    result_show.changjiaId = item.厂家ID;
                    result_show.chengbenjunjia = item.成本均价;
                    result_show.ccwdsl = item.出厂未定数量;
                    result_show.cunhuo = item.存货;
                    result_show.djwssl = item.定价未售数量;
                    result_show.jiacha = item.价差;
                    result_show.kcjj = item.库存均价;
                    result_show.kcsl = item.库存数量;
                    result_show.licha = item.利差;
                    result_show.maolie = item.毛利额;
                    result_show.shoujia = item.售价;
                    result_show.xxjj = item.销售均价;
                    result_show.ztsl = item.在途数量;
                    result_show.zje = item.总金额;
                    result_show.zyf = item.总运费;
                    resultShow.Add(result_show);
                }
            }
            return resultShow.ToArray();
        }

        public class NowDepotProfitReportShow
        {
            public decimal zje { get; set; }
            public decimal zyf { get; set; }
            public string cangku { get; set; }
            public Guid cangkuId { get; set; }
            public string changjia { get; set; }
            public Guid changjiaId { get; set; }
            public decimal chengbenjunjia { get; set; }
            public decimal ccwdsl { get; set; }
            public decimal cunhuo { get; set; }
            public decimal djwssl { get; set; }
            public decimal jiacha { get; set; }
            public decimal kcjj { get; set; }
            public decimal kcsl { get; set; }
            public decimal licha { get; set; }
            public decimal maolie { get; set; }
            public decimal shoujia { get; set; }
            public decimal xxjj { get; set; }
            public decimal ztsl { get; set; }
        }

        /// <summary>
        /// 日经营分析报表-库存权益-根据厂家进行统计
        /// </summary>
        /// <param name="supplierId">厂家ID</param>
        /// <returns></returns>
        [Route("GetNowDepotProfitReportList")]
        [HttpGet]
        public NowDepotProfitReportShow[] GetNowDepotProfitReportList(Guid? supplierId)
        {
            var bll = new NowDepotProfitReportBLL();
            var result = nowDepotProfitReportBLL.GetNowDepotProfitReportList(supplierId).ToList();

            List<NowDepotProfitReportShow> resultShow = new List<NowDepotProfitReportShow>();
            if (result != null && result.Count > 0)
            {
                foreach (var item in result)
                {
                    NowDepotProfitReportShow result_show = new NowDepotProfitReportShow();
                    result_show.cangku = item.仓库;
                    result_show.cangkuId = item.仓库ID;
                    result_show.changjia = item.厂家;
                    result_show.changjiaId = item.厂家ID;
                    result_show.chengbenjunjia = item.成本均价;
                    result_show.ccwdsl = item.出厂未定数量;
                    result_show.cunhuo = item.存货;
                    result_show.djwssl = item.定价未售数量;
                    result_show.jiacha = item.价差;
                    result_show.kcjj = item.库存均价;
                    result_show.kcsl = item.库存数量;
                    result_show.licha = item.利差;
                    result_show.maolie = item.毛利额;
                    result_show.shoujia = item.售价;
                    result_show.xxjj = item.销售均价;
                    result_show.ztsl = item.在途数量;
                    result_show.zje = item.总金额;
                    result_show.zyf = item.总运费;
                    resultShow.Add(result_show);
                }
            }
            return resultShow.ToArray();
        }


        /// <summary>
        /// 日经营分析报表-库存权益-导出
        /// </summary>
        /// <param name="isHander"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="deptId"></param>
        /// <returns></returns>
        [Route("ExpNowDepotProfitReport")]
        [HttpGet]
        public HttpResponseMessage ExpNowDepotProfitReport(Guid? supplierId)
        {
            var result = nowDepotProfitReportBLL.GetNowDepotProfitReportList(supplierId);

            var expData = new List<List<string>>();
            HttpResponseMessage msg = null;
            var nameArray = new string[] { "厂家", "仓库", "定价未售数量", "库存数量", "在途数量", "库存均价", "售价", "利差", "毛利额", "出厂未定数量" };

            foreach (var item in result)
            {
                var data = new List<String>();
                data.Add(item.厂家);
                data.Add(item.仓库);
                data.Add(item.定价未售数量.ToString());
                data.Add(item.库存数量.ToString());
                data.Add(item.在途数量.ToString());
                data.Add(item.库存均价.ToString());
                data.Add(item.售价.ToString());
                data.Add(item.利差.ToString());
                data.Add(item.毛利额.ToString());
                data.Add(item.出厂未定数量.ToString());
                expData.Add(data);
            }
            msg = CsvExp("日经营分析报告-库存权益.csv", expData.ToArray(), nameArray);
            return msg;
        }
        ///// <summary>
        ///// 导出到excel  采销情况
        ///// </summary>
        ///// <param name="isHander"></param>
        ///// <param name="startTime"></param>
        ///// <param name="endTime"></param>
        ///// <param name="providerType"></param>
        ///// <returns></returns>
        //[Route("ExportToExcelSalesReport")]
        //[HttpGet]
        //public void ExportToExcelSalesReport(bool isHander = true, DateTime? startTime=null, DateTime? endTime=null, int? providerType=null)
        //{
        //    var bll = new SalesReportBLL();
        //    var dtData = bll.GetSalesReport(isHander, startTime, endTime, providerType);
        //    string shtnl = "";
        //    shtnl = "<table border='1' cellspacing='1' cellpadding='1'>";
        //    shtnl = shtnl + "<thead>";
        //    for (int j = 0; j < dtData.Columns.Count; j++)
        //    {
        //        shtnl = shtnl + "<th>" + j + "</th>";
        //    }
        //    shtnl = shtnl + "</thead><tbody>";
        //    for (int i = 0; i < dtData.Rows.Count; i++)
        //    {
        //        shtnl = shtnl + "<tr>";
        //        for (int j = 0; j < dtData.Columns.Count; j++)
        //        {
        //            shtnl = shtnl + "<td>" + dtData.Rows[i][j] + "</td>";
        //        }
        //        shtnl = shtnl + "</tr>";
        //    }
        //    shtnl = shtnl + "</tbody></table>"; 
        //    ExportToExcel("application/x-excel", "采销情况.xls", shtnl);
        //}
        //public void ExportToExcel(string FieldType, string FileName, string dt)
        //{
        //    System.Web.HttpContext.Current.Response.Charset = "utf-8";
        //    System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8).ToString());
        //    System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        //    System.Web.HttpContext.Current.Response.ContentType = FieldType;
        //    StringWriter tw = new StringWriter();
        //    System.Web.HttpContext.Current.Response.Output.Write(dt);
        //    System.Web.HttpContext.Current.Response.Flush();
        //    System.Web.HttpContext.Current.Response.End();
        //}  
    }
}